package com.dykj.fireFighting.web.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dykj.fireFighting.api.base.effecttimesetting.entity.EffectiveTimeSetting;
import com.dykj.fireFighting.api.base.effecttimesetting.service.IEffectiveTimeSettingService;
import com.dykj.fireFighting.api.base.effecttimesetting.vo.EffectiveTimeSettingVo;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.base.file.service.OfficeService;
import com.dykj.fireFighting.api.socialUnit.devicemanger.dto.DeviceInfoDto;
import com.dykj.fireFighting.api.socialUnit.devicemanger.entity.DeviceInfo;
import com.dykj.fireFighting.api.socialUnit.devicemanger.service.IDeviceInfoService;
import com.dykj.fireFighting.api.socialUnit.xfxg.dto.PatrolReportDto;
import com.dykj.fireFighting.api.socialUnit.xfxg.entity.FireGroup;
import com.dykj.fireFighting.api.socialUnit.xfxg.entity.PatrolPlan;
import com.dykj.fireFighting.api.socialUnit.xfxg.entity.PatrolReport;
import com.dykj.fireFighting.api.socialUnit.xfxg.entity.PatrolReportRecord;
import com.dykj.fireFighting.api.socialUnit.xfxg.service.IFireGroupService;
import com.dykj.fireFighting.api.socialUnit.xfxg.service.IPatrolPlanService;
import com.dykj.fireFighting.api.socialUnit.xfxg.service.IPatrolReportRecordService;
import com.dykj.fireFighting.api.socialUnit.xfxg.service.IPatrolReportService;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.utils.DateUtil;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import javax.management.Query;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.*;


/**
 * 消防巡查手机接口
 *
 * @Author lch
 * @Date  2021-07-05 15:28
 */
@Slf4j
@Api(value = "消防巡更-巡更报告接口", tags = {"消防巡更-巡更报告接口"})
@RestController
@RequestMapping("/app/patrolReport")
public class PatrolReportRecordController {

    @DubboReference
    private IPatrolReportService patrolReportService;

    @DubboReference
    private IPatrolPlanService patrolPlanService;

    @DubboReference
    private IDeviceInfoService deviceInfoService;

    @DubboReference
    private IPatrolReportRecordService patrolReportRecordService;

    @DubboReference(check = false)
    private OfficeService officeService;

    @DubboReference
    private IFireGroupService fireGroupService;
    @DubboReference
    private IEffectiveTimeSettingService effectiveTimeSettingService;
    @DubboReference
    private IEnterpriseService enterpriseService;
    /**
     * 判断时间是否在时间段内
     * @param nowTime 当前时间
     * @param beginTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    public static boolean belongCalendar(Date nowTime,Date beginTime,Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 消防群组查询设备信息
     *
     * @return
     */
    @AutoLog(value = "消防群组查询设备信息")
    @ApiOperation(value = "消防群组查询设备信息", notes = "消防群组查询设备信息")
    @GetMapping("/deviceList/{id}")
  /*  @RequiresPermissions("app/deviceList/list")*/
    public CommonResult<PageVo<DeviceInfo>> treeGrid(DeviceInfoDto commonDto, @PathVariable("id") String id) {
        commonDto.setTempId(id);
        PageVo<DeviceInfo> page = deviceInfoService.pageList(commonDto);
        return CommonResult.success(page);
    }

    /**
     * 消防群组查询设备信息
     *
     * @return
     */
    @AutoLog(value = "消防群组查询设备信息")
    @ApiOperation(value = "消防群组查询设备信息", notes = "消防群组查询设备信息")
    @GetMapping("/deviceListAddGroup/{id}")
    /*  @RequiresPermissions("app/deviceList/list")*/
    public CommonResult<Map<String,Object>> treeGridAddGroup(DeviceInfoDto commonDto, @PathVariable("id") String id) {
        commonDto.setTempId(id);
        PageVo<DeviceInfo> page = deviceInfoService.pageList(commonDto);
        FireGroup group=fireGroupService.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("list",page);
        map.put("group",group);
        return CommonResult.success(map);
    }

    /**
     * 消防群组查询设备信息
     *
     * @return
     */
    @AutoLog(value = "巡更计划列表")
    @ApiOperation(value = "巡更计划列表", notes = "巡更计划列表")
    @GetMapping("/patrolPlan")
    /*  @RequiresPermissions("app/deviceList/list")*/
    public CommonResult<List<PatrolPlan>> getPatrolPlan(PatrolReportDto commonDto) {
        LoginUserVo loginUserVo = ShiroUtil.getUser();
        List<PatrolPlan> list = patrolPlanService.queryList(loginUserVo.getEnterpriseId().toString());
        return CommonResult.success(list);
    }

    /**
     * 保存巡查
     */
    //@AutoLog(value = "消防巡更-巡更报告-保存消防巡更-巡更报告信息")
    @ApiOperation(value = "保存消防巡更-巡更报告信息", notes = "保存消防巡更-巡更报告信息")
    @PostMapping("/save")
   /* @RequiresPermissions("app/patrolReport/save")*/
    public CommonResult save(@RequestBody PatrolReport patrolReport) {
        try {
            String id = UUIDUtils.get32UUID();
            LoginUserVo loginUserVo = ShiroUtil.getUser();
            patrolReport.setId(id);
            patrolReport.setUnitId(loginUserVo.getEnterpriseId().toString());
            Date date = new Date();
            patrolReport.setCreateTime(date);
            patrolReport.setCreateBy(patrolReport.getPatrolPersion());
            patrolReport.setPatrolTime(date);
            // 获取巡更时间
            Date patrolTime = patrolReport.getPatrolTime();
            // 获取该单位所有计划
            //List<PatrolPlan> plans = patrolPlanService.queryList(loginUserVo.getEnterpriseId().toString());
            PatrolPlan plan=patrolPlanService.getById(patrolReport.getPlanId());
            //获取有效时间
            Enterprise enterprise=enterpriseService.getInfoByBindingCode(loginUserVo.getBindingCode());
            if(null!=enterprise){
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String planTime= DateUtil.getNowDateStr()+" "+plan.getEndTime();
                Date planDateTime=sdf.parse(planTime);
                EffectiveTimeSettingVo effectiveTimeSettingVo = effectiveTimeSettingService.isEffective(planDateTime, "patrol", enterprise.getId().toString());
                if (effectiveTimeSettingVo.getIsEffective()) {
                    patrolReport.setIsQualified(0);
                } else {
                    patrolReport.setIsQualified(1);
                }
            }else{
                patrolReport.setIsQualified(0);
            }

            // 比较时间
            /*for (PatrolPlan plan : plans) {
                if (belongCalendar(patrolTime,plan.getBeginTime(),plan.getEndTime())) {
                    patrolReport.setPlanId(plan.getId());
                }
            }*/
            boolean save = patrolReportService.save(patrolReport);
            List<PatrolReportRecord> reportVo = patrolReport.getPatrolReportRecordList();
            if (save) {
                 for(int i =0;i<reportVo.size();i++) {
                    PatrolReportRecord patrolReportRecord = new PatrolReportRecord();
                    patrolReportRecord.setCreateTime(date);
                    patrolReportRecord.setCreateBy(patrolReport.getPatrolPersion());
                    patrolReportRecord.setPatrolReportId(id);
                    patrolReportRecord.setDeviceId(reportVo.get(i).getDeviceId());
                    patrolReportRecord.setDeviceName(reportVo.get(i).getDeviceName());
                    patrolReportRecord.setFireGroupId(reportVo.get(i).getFireGroupId());
                    FireGroup byId = fireGroupService.getById(reportVo.get(i).getFireGroupId());
                    patrolReportRecord.setFireGroupName(byId.getName());
                    patrolReportRecord.setStatus(reportVo.get(i).getStatus());
                    patrolReportRecord.setType(reportVo.get(i).getType());
                    patrolReportRecordService.save(patrolReportRecord);
                 }
                Map<String,Object> map=new HashMap<>();
                List<PatrolReportRecord> list = patrolReportRecordService.getList(id);
                map.put("list", list);
                String ids = officeService.excelToPdfSave(map, "InspectionReport.xlsx", "巡查报告.pdf");
                PatrolReport patrolReport1 = new PatrolReport();
                patrolReport1.setId(id);
                patrolReport1.setFileId(ids);
                patrolReportService.updateById(patrolReport1);
            }
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 消防巡查列表
     *
     * @return
     */
    @AutoLog(value = "消防巡更-巡更报告-分页列表查询")
    @ApiOperation(value = "消防巡更-巡更报告分页列表", notes = "消防巡更-巡更报告分页列表")
    @GetMapping("/list")
  /*  @RequiresPermissions("app/patrolReport/list")*/
    public CommonResult<PageVo<PatrolReport>> treeGrid(PatrolReportDto commonDto) {
        LoginUserVo loginUserVo = ShiroUtil.getUser();
        commonDto.setUnitId(loginUserVo.getEnterpriseId().toString());
        PageVo<PatrolReport> page = patrolReportService.pageList(commonDto);
        return CommonResult.success(page);
    }

    /**
     * 巡查详情
     */
    @AutoLog(value = "消防巡更-巡更报告-获取消防巡更-巡更报告信息")
    @ApiOperation(value = "获取消防巡更-巡更报告信息", notes = "获取消防巡更-巡更报告信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", dataType = "String", required = true)
    @GetMapping("/info/{id}")
    /*@RequiresPermissions("app/patrolReport/info")*/
    public CommonResult<PatrolReport> info(@PathVariable("id") String id){
        PatrolReport patrolReport = patrolReportService.getById(id);
        return CommonResult.success(patrolReport);
    }


    /**
     * 巡查报告设备异常报表
     *
     * @return
     */
    @AutoLog(value = "巡更报告记录表-异常设备列表查询")
    @ApiOperation(value = "巡更报告记录表-异常设备列表查询", notes = "巡更报告记录表-异常设备列表查询")
    @GetMapping("/statusList/{patrolReportId}")
    public CommonResult<List<PatrolReportRecord>> recordList(@PathVariable("patrolReportId") String patrolReportId) {
        List<PatrolReportRecord> ycList = patrolReportRecordService.getYcList(patrolReportId);
        return CommonResult.success(ycList);
    }


}
